import os
from functools import wraps

from flask import jsonify, make_response, g, request, session, Response

from run import app
from exts import auth

from app.models import QUserInfo
from app.utils.error import ResponseError


def exception_handling(func):
    '''
    异常处理
    :param func:
    :return:
    '''

    @wraps(func)
    def inner(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            return res
        except ResponseError as e:
            isSqlError = e.__getattribute__('isSqlError')
            print(func.__name__, 'error:', e)
            return jsonify(code=e.__getattribute__('code'), msg='网络错误，请重试' if isSqlError else e.__getattribute__('msg'),
                           data={'errMsg': str(e) if app.config['ENV'] != 'production' else 'some error'})
        except Exception as e:
            return jsonify(code=-1, msg='网络错误，请重试',
                           data={'errMsg': str(e) if app.config['ENV'] != 'production' else 'some error'})

    return inner


def exception_handling_img(func):
    '''
    图片异常处理
    :param func:
    :return:
    '''

    @wraps(func)
    def inner(*args, **kwargs):
        try:
            res = func(*args, **kwargs)
            return res
        except Exception as e:
            print(func.__name__, 'img error', e)
            file = os.path.join(app.config['FILE_PATH'], 'share_error.png')
            with open(file, 'rb') as f:
                image = f.read()
            return Response(image, mimetype="image/jpeg")

    return inner


@auth.verify_token
def callback(token):
    '''
    token校验，username_or_token是curl -u http://user:pwd@localhost:8000
    :param token:
    :return:
    '''
    theToken = token if token else request.headers.get(app.config['TOKEN_KEY'])
    theToken = theToken if theToken else (session['token'] if 'token' in session else None)
    if theToken:
        user = QUserInfo.verify_auth_token(theToken)
        if user:
            g.user = user
            return True
    return False


@auth.error_handler
def unauthorized():
    '''未授权错误'''
    return make_response(jsonify({'code': -2, 'msg': 'Unauthorized access'}), 401)
